
package com.webframe.web.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.mlw.vlh.ValueList;

import org.apache.commons.beanutils.BasicDynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.webframe.service.impl.TableOperationService;

@Controller
@RequestMapping("/extExportExcel")
public class ExtExportExcelController extends ValueListController
{

	@Autowired
	TableOperationService			tableOperationService;

	@Autowired
	private ValueListController	valueListController;

	// 创建工作本
	public HSSFWorkbook				demoWorkBook	= null;

	public static final int			columNumber		= 18;

	OutputStream						fos				= null;

	// 每页限定的行数
	public static int					PAGESIZE			= 5000;

	private int							sheetSize		= 1;

	// 创建表
	public HSSFSheet[]				sheets;

	// 处理复杂表头
	private String[][]				headerNames		= null;

	private int[][]					headerColspan	= null;

	@SuppressWarnings({
				"rawtypes", "unchecked"})
	@RequestMapping("/export")
	public String export(HttpServletRequest req, HttpServletResponse res)
				throws Exception
	{
		res.setHeader("Content-Type", "application/force-download");
		res.setHeader("Content-Type", "application/octet-stream");
		String fileName = encodeFileName(req, req.getParameter("filename"));
		res.setHeader("Content-Disposition", "attachment;filename="
					+ fileName
					+ ".xls");
		String key = req.getParameter("key"); // key
		Map queries = new HashMap();
		Iterator it = req.getParameterMap().keySet().iterator();
		Object tmp;
		while (it.hasNext())
		{
			tmp = it.next();
			queries.put(tmp, req.getParameter(tmp.toString()));
		}
		ValueList list = null;
		list = valueListController.getAllValueList(key, req);
		int totalSize = list.getValueListInfo().getTotalNumberOfEntries();
		sheetSize = (totalSize + PAGESIZE - 1) / PAGESIZE;// 分页
		demoWorkBook = new HSSFWorkbook();
		sheets = new HSSFSheet[sheetSize];
		try
		{
			for (int page = 0; page < sheetSize; page++)
			{
				sheets[page] = demoWorkBook.createSheet("Sheet" + page);
				int realSizePerSheet = PAGESIZE * (page + 1);
				if (totalSize < (page + 1) * PAGESIZE)
				{
					realSizePerSheet = totalSize;
				}
				for (int i = page * PAGESIZE, k = 0; i < realSizePerSheet; i++, k++)
				{
					// createTableRow(sheets[page],(BasicDynaBean)list.getList().get(i),k);
					if ((req.getParameter("custom_header_grid_") != null)
								&& req.getParameter("custom_header_grid_")
									.equalsIgnoreCase("true"))
					{
						doHeader(sheets[page], (BasicDynaBean) list.getList().get(i),
							k);
					} else
					{
						createTableRow(sheets[page], (BasicDynaBean) list.getList()
							.get(i), k);
					}
				}
				sheets[page].setGridsPrinted(true);
			}
			fos = res.getOutputStream();
			demoWorkBook.write(fos);
			fos.flush();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if (fos != null) fos.close();
				fos = null;
				sheets = null;
				list = null;
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 创建行
	 * 
	 * @param hssSheet
	 * @param listOrderedMap
	 * @param index
	 */
	public void createTableRow(HSSFSheet hssSheet, BasicDynaBean dynaBean, int index)
	{
		HSSFRow row = null;
		HSSFCell cell = null;
		DynaProperty[] dynaProperties = dynaBean.getDynaClass()
			.getDynaProperties();
		hssSheet.setDefaultColumnWidth(20);
		HSSFCellStyle style = demoWorkBook.createCellStyle();
		HSSFFont f = demoWorkBook.createFont();
		f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
		style.setFont(f);
		// 创建标题
		if (hssSheet.getRow(0) == null)
		{
			row = hssSheet.createRow(0);
			for (int i = 0; i < dynaProperties.length; i++)
			{
				cell = row.createCell(i);
				cell.setCellStyle(style);
				cell.setCellValue(dynaProperties[i].getName().toString());
			}
		}
		row = hssSheet.createRow(index + 1);
		for (int i = 0; i < dynaProperties.length; i++)
		{
			cell = row.createCell(i);
			if (dynaBean.get(dynaProperties[i].getName()) != null)
			{
				cell.setCellValue(dynaBean.get(dynaProperties[i].getName())
					.toString());
			} else
			{
				cell.setCellValue("-");
			}
		}
	}

	public void doHeader(HSSFSheet hssSheet, BasicDynaBean dynaBean, int index)
	{
		HSSFRow row = null;
		HSSFCell cell = null;
		// 样式
		HSSFCellStyle style = demoWorkBook.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_BOTTOM);
		if (null == hssSheet.getRow(0))
		{
			for (int i = 0; i < headerNames.length; i++)
			{//
				HSSFRow tRow = hssSheet.createRow(i);
				for (int j = 0, k = 0; j < headerNames[i].length; j++)
				{
					Region tRegion = new Region(i, (short) k, i, (short) (k - 1 + headerColspan[i][j]));
					hssSheet.addMergedRegion(tRegion);
					HSSFCell tCell = tRow.createCell(k);
					if ("recordnum".equals(headerNames[i][j]))
					{
						tCell.setCellValue("");
					} else
					{
						tCell.setCellValue(headerNames[i][j]);
					}
					tCell.setCellStyle(style);
					k += headerColspan[i][j];
				}
			}
		}
		DynaProperty[] dynaProperties = dynaBean.getDynaClass()
			.getDynaProperties();
		row = hssSheet.createRow(index + headerNames.length);
		for (int i = 0; i < dynaProperties.length; i++)
		{
			cell = row.createCell(i);
			String propertyName = dynaProperties[i].getName();
			if (null != propertyName && !"recordnum".equals(propertyName))
			{
				if (null != dynaBean.get(propertyName))
				{
					cell.setCellValue(dynaBean.get(propertyName).toString());
				}
			} else
			{
				cell.setCellValue("");
			}
		}
	}

	public static String encodeFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
	{
		String agent = request.getHeader("USER-AGENT");
		if (null != agent && -1 != agent.indexOf("MSIE"))
		{
			return fileName;
		} 
		else if (null != agent && -1 != agent.indexOf("Firefox"))
		{
			fileName = URLDecoder.decode(fileName, "UTF-8");
			return "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
		} 
		else
		{
			return fileName;
		}
	}
}
